package com.atguigu.service.impl;

import com.atguigu.feign.UserFeignClient;
import com.atguigu.mapper.OrderMapper;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.Person;
import com.atguigu.pojo.User;
import com.atguigu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@RefreshScope // 热更新获取配置中心的最新数据
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    // 远程调用模板对象
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private Person person;
    @Override
    public Order getOrderById(Integer id) {

        Order order = orderMapper.getOrderById(id);
        // 远程连接
        // 方式 1
//        User user = restTemplate.getForObject("http://localhost:10100/api/user/getUserById/"+order.getUserId(),User.class);
        // 方式 2
        List<ServiceInstance> instances = discoveryClient.getInstances("spzx-cloud-user");
        // 随机获取 nacos的实例
//        ServiceInstance serviceInstance = instances.get(new Random().nextInt(instances.size()));
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        User user = restTemplate.getForObject("http://"+host+":"+port+"/api/user/getUserById/"+order.getUserId(),User.class);

        // 方式3 // 负载均衡器  根据供给端服务名 下载服务实例
//        User user = restTemplate.getForObject("http://spzx-cloud-user/api/user/getUserById/"+order.getUserId(),User.class);

        // 方式4 使用 OPenFeign    进行远程调用
        User user = userFeignClient.getUserById(order.getUserId());
        order.setUser(user);
        order.setPerson(person);
        return order;
    }
}
